package com.example.service.customer.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.example.service.api.dto.CustomerDTO;
import com.example.service.customer.entity.CustomerPO;
import com.example.service.customer.entity.param.CustomerParams;
import com.example.service.customer.mapper.CustomerMapper;
import com.example.service.customer.service.CustomerService;
import com.example.stack.constant.ErrorCode;
import com.example.stack.exception.FailException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.stack.exception.InternalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, CustomerPO> implements CustomerService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public CustomerDTO insertCustomer(CustomerDTO customerDTO) {

        CustomerPO customerPO = new CustomerPO();
        BeanUtils.copyProperties(customerDTO, customerPO);
        //雪花算法生成id
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long id = snowflake.nextId();
        logger.info("生成客户id={}",id);

        customerDTO.setCustomerId(String.valueOf(id));
        this.save(customerPO);
        logger.info("插入客户信息成功");

        customerDTO.setCustomerId(customerPO.getCustomerId());
        return customerDTO;
    }

    @Override
    public void deleteCustomerInfo(String id) {
        boolean result = this.removeById(id);
        if (!result) {
            throw new InternalException(ErrorCode.DELETE_FAIL, "删除失败");
        }
    }

    @Override
    public CustomerDTO updateCustomerInfo(CustomerDTO customerDTO) {

        CustomerPO customerPO = new CustomerPO();
        // 属性拷贝
        BeanUtils.copyProperties(customerDTO, customerPO);
        this.updateById(customerPO);

        return customerDTO;
    }

    @Override
    public CustomerDTO getCustomerById(String customerId) {
        CustomerPO customerPO = this.getById(customerId);
        if(customerPO == null)
            return null;

        CustomerDTO customerDTO = new CustomerDTO();
        customerDTO.setCustomerId(customerPO.getCustomerId());
        customerDTO.setIdNumber(customerPO.getIdNumber());
        customerDTO.setName(customerPO.getName());

        return customerDTO;
    }
}
